using System;
using System.Linq;
using System.Collections.Generic;

namespace ContinualFlame.Ajax
{	
	// TODO: this will need to be database-backed eventually (reduce memory footprint)
	
	// object representing a bag of objects that is kept in sync across clients
	// (items are optionally named - dictionary vs. list)
	public class SynchronizedSet : SynchronizedObject
	{
		object _lock = new object();
		Dictionary<string, Message> _set = new Dictionary<string, Message>();
		
		public SynchronizedSet(string name) :
			base(name)
		{
		}
		
		public void Add(Message m)
		{
			lock (_lock)
			{
				// allow 'replace' for dictionaries, but not for simple lists
				
				string name = (m.Name == null) ? 
					m.Watermark.ToString() : m.Name;
				
				_set[name] = m;

                m.Source = this.Name;

				Owner.Deliver(this, m);
			}
		}
		
		public override IEnumerable<Message> GetDelta (long watermark)
		{
			lock (_lock)
			{
				// return a snapshot (lock-safe, forces early evaluation for sane debugging)
				
				return _set
					.Where(x => x.Value.Watermark > watermark)
					.Select(x => x.Value)
					.ToList();		
			}
		}

	}
}
